<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>Algorithm::Loops - Looping constructs: NestedLoops, MapCar*, Filter, and NextPermute* - metacpan.org</title>
        <link rel="preload" as="fetch" href="https://metacpan.org/account/login_status" crossorigin="anonymous" />
        <link href="https://metacpan.org/_assets/b8ccceeed47a0652049703d99326a9cea4933443.css" rel="stylesheet" type="text/css">
        <script src="https://metacpan.org/_assets/6bfedafe2d7caa915b7d84f61b45936818e3242e.js" type="text/javascript" defer></script>
        <link rel="alternate" type="application/rss+xml" title="Recent CPAN Uploads of Algorithm-Loops - MetaCPAN" href="https://metacpan.org/dist/Algorithm-Loops/releases.rss" />
        <link rel="canonical" href="./Algorithm::Loops.html" />
        <meta name="description" content="Looping constructs: NestedLoops, MapCar*, Filter, and NextPermute*" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5">
        <link rel="shortcut icon" href="https://metacpan.org/static/icons/favicon.ico">
        <link rel="apple-touch-icon" sizes="152x152" href="https://metacpan.org/static/icons/apple-touch-icon.png">
        <link rel="search" href="https://metacpan.org/static/opensearch.xml" type="application/opensearchdescription+xml" title="MetaCPAN">
        <script>
          (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
          })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

          (function(skey, ga_id){
            ga('create', ga_id, {
              siteSpeedSampleRate : 100,
              storage             : 'none',
              clientId            : localStorage.getItem(skey)
            });
            ga(function(tracker) {
              localStorage.setItem(skey, tracker.get('clientId'));
            });
            ga('send', 'pageview');
          })('ga:clientId', 'UA-27829474-1');
        </script>
<meta name="twitter:card"        content="summary" />
<meta name="twitter:url"         content="https://metacpan.org/pod/Algorithm::Loops" />
<meta name="twitter:title"       content="Algorithm::Loops" />
<meta name="twitter:description" content="Looping constructs: NestedLoops, MapCar*, Filter, and NextPermute*" />
<meta name="twitter:site"        content="metacpan" />
    </head>
    <body>
        <nav class="navbar navbar-default" role="navigation">
            <div class="header-logo-large hidden-xs">
              <a href="https://metacpan.org/" tabindex="0">
                <svg class="logo" aria-label="MetaCPAN">
                  <use class="logo" href="/static/images/metacpan-logo.svg#logo" />
                </svg>
              </a>
            </div>
            <div class="header-logo-icon visible-xs">
              <a href="https://metacpan.org/">
                <svg class="logo" aria-label="MetaCPAN">
                  <use class="logo" href="/static/images/metacpan-logo.svg#dots" />
                </svg>
              </a>
            </div>
            <ul class="nav navbar-nav menu-items hidden-xs hidden-sm">
              <li><a href="https://metacpan.org/about">About</a></li>
              <li><a href="https://metacpan.org/about/sponsors">Sponsor</a></li>
              <li><a href="https://grep.metacpan.org/">grep::cpan</a></li>
              <li><a href="https://metacpan.org/recent">Recent</a></li>
              <li><a href="https://metacpan.org/about/faq">FAQ</a></li>
              <li><a href="https://metacpan.org/tools">Tools</a></li>
              <li><a href="https://fastapi.metacpan.org/">API</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <button type="button" class="searchbar-btn visible-xs visible-sm">
                    <i class="fa fa-search button-fa-icon"></i>
                </button>
                <form action="https://metacpan.org/search" class="searchbar-form visible-md visible-lg search-form form-horizontal">
                   <input type="hidden" name="size" id="metacpan_search-size" value="20">
                  <div class="form-group">
                      <div class="search-group">
                        <i class="fa fa-search"></i>
                        <input type="text" name="q" placeholder="Search the CPAN" size="41" autocorrect="off" autocapitalize="off" spellcheck="false" id="metacpan_search-input" class="form-control" value="">
                      </div>
                  </div>
                </form>
                    <li class="icon-slidepanel visible-xs visible-sm">
                      <button data-toggle="slidepanel" data-target=".slidepanel">
                        <span class="button-fa-icon">
                          <i class="fa fa-bars slidepanel-open"></i>
                          <i class="fa fa-times slidepanel-close"></i>
                        </span>
                      </button>
                    </li>
                <form action="https://metacpan.org/account/logout" method="POST" id="metacpan-logout"></form>
                <li class="dropdown logged_in" style="display: none;">
                    <button type="button" class="dropdown-toggle" data-toggle="dropdown">
                      <i class="fa fa-user button-fa-icon logged-in-icon" aria-hidden="true"></i>
                      <i class="fas fa-chevron-down"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a href="https://metacpan.org/account/identities">Identities</a></li>
                        <li><a href="https://metacpan.org/account/profile">Profile</a></li>
                        <li><a href="https://metacpan.org/account/favorite/list">Favorites</a></li>
                        <li>
                            <a href="./Algorithm::Loops.html#" type="button" onclick="$('#metacpan-logout').submit(); return false">
                              Logout
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="dropdown logged_out" style="display: none;">
                    <button type="button" class="dropdown-toggle" data-toggle="dropdown">
                      <i class="fa fa-user button-fa-icon" aria-hidden="true"></i>
                      <i class="fas fa-chevron-down"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a href="https://metacpan.org/login/github">
                                <i class="fab fa-github fa-fw"></i>
                                GitHub
                            </a>
                        </li>
                        <li>
                            <a href="https://metacpan.org/login/twitter">
                                <i class="fab fa-twitter fa-fw"></i>
                                Twitter
                            </a>
                        </li>
                        <li>
                            <a href="https://metacpan.org/login/google">
                                <i class="fab fa-google fa-fw"></i>
                                Google
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="dropdown logged_placeholder">
                    <button>
                      <i class="fa fa-user button-fa-icon" aria-hidden="true"></i>
                    </button>
                </li>
            </ul>
        </nav>
        <div class="page-content ">
          <!--
          <div class="top-notify-banner">
            <i class="fas fa-info-circle"></i>
          </div>
          -->
          <nav class="sidebar">
            <div class="slidepanel">
              <ul class="nav-list ">
    <li class="nav-header no-margin-top">
      <div class="ttip" data-toggle="tooltip" data-placement="bottom" title="The date that this version of Algorithm-Loops was released.">
      <span class="relatize">24 Jul 2016 03:23:01 UTC</span>
    </li>
  <li>
    Distribution: <a href="https://metacpan.org/dist/Algorithm-Loops">Algorithm-Loops</a>
  </li>
  <li>
    Module version: 1.032
  </li>
  <li>
    <a data-keyboard-shortcut="g s" href="https://metacpan.org/dist/Algorithm-Loops/source/lib/Algorithm/Loops.pm">Source</a>
    (<a href="https://metacpan.org/dist/Algorithm-Loops/source/lib/Algorithm/Loops.pm?raw=1">raw</a>)
  </li>
  <li>
    <a data-keyboard-shortcut="g b" href="https://metacpan.org/dist/Algorithm-Loops/source/lib/Algorithm">Browse</a>
    (<a href="https://metacpan.org/dist/Algorithm-Loops/source/lib/Algorithm?raw=1">raw</a>)
  </li>
    <li>
      <a data-keyboard-shortcut="g c" href="https://metacpan.org/dist/Algorithm-Loops/changes">Changes</a>
    </li>
    <li>
      <a class="nopopup" href="https://metacpan.org/dist/Algorithm-Loops/contribute">How to Contribute</a>
    </li>
    <li>
      <a rel="noopener nofollow" data-keyboard-shortcut="g i" href="https://rt.cpan.org/Public/Dist/Display.html?Name=Algorithm-Loops">Issues</a>
      (2)
    </li>
    <li>
      <a rel="noopener nofollow" href="http://matrix.cpantesters.org/?dist=Algorithm-Loops+1.032" title="Matrix">Testers</a>
        <span title="(pass / fail / na)">(<a rel="noopener nofollow" href="https://www.cpantesters.org/distro/A/Algorithm-Loops.html?oncpan=1&amp;distmat=1&amp;version=1.032&amp;grade=2" style="color: #090">1138</a> / <a rel="noopener nofollow" href="https://www.cpantesters.org/distro/A/Algorithm-Loops.html?oncpan=1&amp;distmat=1&amp;version=1.032&amp;grade=3" style="color: #900">0</a> / <a rel="noopener nofollow" href="https://www.cpantesters.org/distro/A/Algorithm-Loops.html?oncpan=1&amp;distmat=1&amp;version=1.032&amp;grade=4">0</a>)</span>
    </li>
    <li>
      <a rel="noopener nofollow" href="http://cpants.cpanauthors.org/release/TYEMQ/Algorithm-Loops-1.032">Kwalitee</a>
    </li>
    <li>
      <div class="ttip" data-toggle="tooltip" data-placement="bottom" title="The # people with an indexing permission on Algorithm-Loops who have released something to CPAN in the last 2 years (i.e. the # people likely able to release critical fixes in a timely manner)">
      Bus factor: 0
      </div>
    </li>
    <li>
      <a rel="noopener nofollow" href="http://cpancover.com/latest/Algorithm-Loops-1.032/index.html">87.15% Coverage </a>
    </li>
    <li>
      License: unrestricted
    </li>
    <li class="nav-header">Activity</li>
    <li>
<div class="activity-graph">
    <img src="https://metacpan.org/dist/Algorithm-Loops/activity.svg?res=month" />
    <div class="comment">24 month</div>
</div>
    </li>
    <li class="nav-header">Tools</li>
    <li>
      <a itemprop="downloadUrl" href="https://cpan.metacpan.org/authors/id/T/TY/TYEMQ/Algorithm-Loops-1.032.tar.gz">
      Download (<span itemprop="fileSize">19.29KB</span>)</a>
    </li>
    <li>
      <a href="https://explorer.metacpan.org/?url=%2Fmodule%2FTYEMQ%2FAlgorithm-Loops-1.032%2Flib%2FAlgorithm%2FLoops.pm">
        MetaCPAN Explorer
      </a>
    </li>
    <li>
      <a href="https://metacpan.org/dist/Algorithm-Loops/permissions">
        Permissions
      </a>
    </li>
    <li>
      <a href="https://metacpan.org/dist/Algorithm-Loops/releases.rss">
        Subscribe to distribution
      </a>
    </li>
    <li>
      <button class="btn btn-link" data-toggle="modal" data-target="#metacpan_install-instructions-dialog">
        Install Instructions
      </button>
    </li>
    <li>
      <form action="https://metacpan.org/search">
        <input type="hidden" name="q" value="dist:Algorithm-Loops">
        <input type="search" name="q" placeholder="Search distribution" class="form-control tool-bar-form">
        <input type="submit" style="display: none">
      </form>
    </li>
    <li>
      <form action="https://grep.metacpan.org/search">
        <input type="hidden" name="qd" value="Algorithm-Loops">
        <input type="hidden" name="source" value="metacpan">
        <input type="search" name="q" placeholder="grep distribution" class="form-control tool-bar-form">
        <input type="submit" style="display: none">
     </form>
    </li>
    <li class="version-jump">
<select onchange="document.location.href=&#39;/release/&#39;+this.value+&#39;/view/lib/Algorithm/Loops.pm&#39;" class="form-control tool-bar-form">
  <option disabled selected>Jump to version</option>
<option
  disabled
  value="TYEMQ/Algorithm-Loops-1.032"
>1.032
  (TYEMQ on 2016-07-24)</option>
<option
  
  value="TYEMQ/Algorithm-Loops-1.031"
>1.031
  (TYEMQ on 2003-09-28)</option>
</select>
    </li>
    <li class="version-diff">
<select onchange="document.location.href='/release/TYEMQ/Algorithm-Loops-1.032/diff/' + encodeURIComponent(this.value) + '/lib/Algorithm/Loops.pm'
" class="form-control tool-bar-form">
  <option disabled selected>Diff with version</option>
<option
  disabled
  value="TYEMQ/Algorithm-Loops-1.032"
>1.032
  (TYEMQ on 2016-07-24)</option>
<option
  
  value="TYEMQ/Algorithm-Loops-1.031"
>1.031
  (TYEMQ on 2003-09-28)</option>
</select>
    </li>

    <li>
<ul class="dependencies">
  <li class="nav-header">Dependencies</li>
  <li><i class="ttip" title="dynamic_config enabled">unknown</i></li>
  <li>
    <hr>
  </li>
  <li>
    <a href="https://metacpan.org/module/Algorithm::Loops/requires">Reverse dependencies</a>
  </li>
  <li>
    <a href="http://deps.cpantesters.org/?module=Algorithm%3A%3ALoops">CPAN Testers List</a>
  </li>
  <li>
    <a href="https://cpandeps.grinnz.com/?dist=Algorithm-Loops">Dependency graph</a>
  </li>
</ul>
    </li>
    <li class="nav-header">Permalinks</li>
    <li>
      <a href="https://metacpan.org/release/TYEMQ/Algorithm-Loops-1.032/view/lib/Algorithm/Loops.pm">This version</a>
    </li>
    <li>
      <a href="./Algorithm::Loops.html">Latest version</a>
    </li>
    <li>
    </li>
    <li>
    </li>
              </ul>
            </div>
          </nav>
          <div class="content-navigation">
<div class="breadcrumbs">
  <span>
    <a data-keyboard-shortcut="g a" rel="author" href="https://metacpan.org/author/TYEMQ" class="author-name">Tye McQueen</a>
  </span>
  <span>&nbsp;/&nbsp;</span>
  <div class="release dist-release status-latest maturity-released">
    <span class="dropdown"><b class="caret"></b></span>
<select onchange="document.location.href=&#39;/release/&#39;+this.value+&#39;/view/lib/Algorithm/Loops.pm&#39;" class="">
<option
  selected
  value="TYEMQ/Algorithm-Loops-1.032"
>1.032
  (TYEMQ on 2016-07-24)</option>
<option
  
  value="TYEMQ/Algorithm-Loops-1.031"
>1.031
  (TYEMQ on 2003-09-28)</option>
</select>
    <a data-keyboard-shortcut="g d" class="release-name" href="https://metacpan.org/dist/Algorithm-Loops">Algorithm-Loops-1.032</a>
  </div>
<span class="river-gauge-gauge">
  <svg width="24px"
       height="15px"
       version="1.1"
       xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink">

    <g>
      <title>        River stage one &#10;
          • 7 direct dependents &#10;          • 9 total dependents
      </title>

      <rect x="0"  y="0" width="4" height="15" fill="#7ea3f2" />
      <rect x="5"  y="0" width="4" height="15" fill="#e4e2e2" />
      <rect x="10"  y="0" width="4" height="15" fill="#e4e2e2" />
      <rect x="15"  y="0" width="4" height="15" fill="#e4e2e2" />
      <rect x="20"  y="0" width="4" height="15" fill="#e4e2e2" />
    </g>
  </svg>

</span>
<div id="Algorithm-Loops-fav" class="logged_in">
<form action="https://metacpan.org/account/favorite/add" style="display: inline" onsubmit="return favDistribution(this)">
    <input type="hidden" name="remove" value="0">
    <input type="hidden" name="release" value="Algorithm-Loops-1.032">
    <input type="hidden" name="author" value="TYEMQ">
    <input type="hidden" name="distribution" value="Algorithm-Loops">
    <button type="submit" class="favorite"><span></span> ++</button>
</form>
</div>
<div class="logged_out">
<a href="./Algorithm::Loops.html" onclick="alert('Please sign in to add favorites'); return false" class="favorite">
<span></span> ++</a>
</div>
   / <span>Algorithm::Loops</span>
</div>
          </div>
          <main class="content">


<nav class="toc">
  <div class="toc-header"><strong>Contents</strong></div>
<ul>
  <li><a href="./Algorithm::Loops.html#NAME">NAME</a></li>
  <li><a href="./Algorithm::Loops.html#SYNOPSYS">SYNOPSYS</a></li>
  <li><a href="./Algorithm::Loops.html#FUNCTIONS">FUNCTIONS</a>
    <ul>
      <li><a href="./Algorithm::Loops.html#Filter(%5C&amp;@)">Filter(\&amp;@)</a>
        <ul>
          <li><a href="./Algorithm::Loops.html#Overview">Overview</a></li>
          <li><a href="./Algorithm::Loops.html#Usage">Usage</a></li>
          <li><a href="./Algorithm::Loops.html#Note-on-%22Function-BLOCK-LIST%22-bugs">Note on &quot;Function BLOCK LIST&quot; bugs</a></li>
          <li><a href="./Algorithm::Loops.html#Examples">Examples</a></li>
          <li><a href="./Algorithm::Loops.html#Motivation">Motivation</a></li>
        </ul>
      </li>
      <li><a href="./Algorithm::Loops.html#MapCar*">MapCar*</a>
        <ul>
          <li><a href="./Algorithm::Loops.html#Usage1">Usage</a></li>
          <li><a href="./Algorithm::Loops.html#Differences">Differences</a></li>
          <li><a href="./Algorithm::Loops.html#Examples1">Examples</a></li>
        </ul>
      </li>
      <li><a href="./Algorithm::Loops.html#NextPermute*">NextPermute*</a>
        <ul>
          <li><a href="./Algorithm::Loops.html#Introduction">Introduction</a></li>
          <li><a href="./Algorithm::Loops.html#Usage2">Usage</a></li>
          <li><a href="./Algorithm::Loops.html#Notes">Notes</a></li>
          <li><a href="./Algorithm::Loops.html#Features">Features</a></li>
          <li><a href="./Algorithm::Loops.html#Notes1">Notes</a></li>
        </ul>
      </li>
      <li><a href="./Algorithm::Loops.html#NestedLoops1">NestedLoops</a>
        <ul>
          <li><a href="./Algorithm::Loops.html#Introduction1">Introduction</a></li>
          <li><a href="./Algorithm::Loops.html#Usage3">Usage</a>
            <ul>
              <li><a href="./Algorithm::Loops.html#%5C@Loops">\@Loops</a></li>
              <li><a href="./Algorithm::Loops.html#%5C%25Opts">\%Opts</a></li>
              <li><a href="./Algorithm::Loops.html#%5C&amp;Code">\&amp;Code</a></li>
              <li><a href="./Algorithm::Loops.html#Iterator">Iterator</a></li>
            </ul>
          </li>
          <li><a href="./Algorithm::Loops.html#Examples2">Examples</a>
            <ul>
              <li><a href="./Algorithm::Loops.html#Finding-non-repeating-sequences-of-digits.">Finding non-repeating sequences of digits.</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul></nav>
<div class="pod anchors">
<h1 id="NAME">NAME</h1>

<p>Algorithm::Loops - Looping constructs: NestedLoops, MapCar*, Filter, and NextPermute*</p>

<h1 id="SYNOPSYS">SYNOPSYS</h1>

<pre><code>    use Algorithm::Loops qw(
        Filter
        MapCar MapCarU MapCarE MapCarMin
        NextPermute NextPermuteNum
        NestedLoops
    );

    my @copy= Filter {tr/A-Z&#39;.,&quot;()/a-z/d} @list;
    my $string= Filter {s/\s*$/ /} @lines;

    my @transposed= MapCarU {[@_]} @matrix;

    my @list= sort getList();
    do {
        usePermutation( @list );
    } while(  NextPermute( @list )  );

    my $len= @ARGV ? $ARGV[0] : 3;
    my @list= NestedLoops(
        [  ( [ 1..$len ] ) x $len  ],
        sub { &quot;@_&quot; },
    );</code></pre>

<p>If you want working sample code to try, see below in the section specific to the function(s) you want to try. The above samples only give a <i>feel</i> for how the functions are typically used.</p>

<h1 id="FUNCTIONS">FUNCTIONS</h1>

<p>Algorithm::Loops provides the functions listed below. By default, no functions are exported into your namespace (package / symbol table) in order to encourage you to list any functions that you use in the <code>use Algorithm::Loops</code> statement so that whoever ends up maintaining your code can figure out which module you got these functions from.</p>

<dl>

<dt id="Filter">Filter</dt>
<dd>

<p>Similar to <code>map</code> but designed for use with s/// and other reflexive operations. Returns a modified copy of a list.</p>

</dd>
<dt id="MapCar,-MapCarU,-MapCarE,-and-MapCarMin"><a id="MapCar"></a><a id="MapCar--MapCarU--MapCarE--and-MapCarMin"></a>MapCar, MapCarU, MapCarE, and MapCarMin</dt>
<dd>

<p>All similar to <code>map</code> but loop over multiple lists at the same time.</p>

</dd>
<dt id="NextPermute-and-NextPermuteNum"><a id="NextPermute"></a>NextPermute and NextPermuteNum</dt>
<dd>

<p>Efficiently find all (unique) permutations of a list, even if it contains duplicate values.</p>

</dd>
<dt id="NestedLoops">NestedLoops</dt>
<dd>

<p>Simulate <code>foreach</code> loops nested arbitrarily deep.</p>

</dd>
</dl>

<h2 id="Filter(\&amp;@)"><a id="Filter1"></a>Filter(\&amp;@)</h2>

<h3 id="Overview">Overview</h3>

<p>Produces a modified copy of a list of values. Ideal for use with s///. If you find yourself trying to use s/// or tr/// inside of map (or grep), then you should probably use Filter instead.</p>

<p>For example:</p>

<pre><code>    use Algorithm::Loops qw( Filter );

    @copy = Filter { s/\\(.)/$1/g } @list;
    $text = Filter { s/^\s+// } @lines;</code></pre>

<p>The same process can be accomplished using a careful and more complex invocation of map, grep, or foreach. However, many incorrect ways to attempt this seem rather seductively appropriate so this function helps to discourage such (rather common) mistakes.</p>

<h3 id="Usage">Usage</h3>

<p>Filter has a prototype specification of (\&amp;@).</p>

<p>This means that it demands that the first argument that you pass to it be a CODE reference. After that you can pass a list of as many or as few values as you like.</p>

<p>For each value in the passed-in list, a copy of the value is placed into $_ and then your CODE reference is called. Your subroutine is expected to modify $_ and this modified value is then placed into the list of values to be returned by Filter.</p>

<p>If used in a scalar context, Filter returns a single string that is the result of:</p>

<pre><code>    $string= join &quot;&quot;, @results;</code></pre>

<p>Note that no arguments are passed to your subroutine (so don&#39;t bother with @_) and any value <code>return</code>ed by your subroutine is ignored.</p>

<p>Filter&#39;s prototype also means that you can use the &quot;map BLOCK&quot;-like syntax by leaving off the <code>sub</code> keyword if you also leave off the comma after the block that defines your anonymous subroutine:</p>

<pre><code>        my @copy= Filter sub {s/\s/_/g}, @list;
  # becomes:            v^^^       v   ^
        my @copy= Filter {s/\s/_/g} @list;</code></pre>

<p>Most of our examples will use this shorter syntax.</p>

<p>Note also that by importing Filter via the <code>use</code> statement:</p>

<pre><code>    use Algorithm::Loops qw( Filter );</code></pre>

<p>it gets declared before the rest of our code is compiled so we don&#39;t have to use parentheses when calling it. We <i>can</i> if we want to, however:</p>

<pre><code>        my @copy= Filter( sub {s/\s/_/g}, @list );</code></pre>

<h3 id="Note-on-&quot;Function-BLOCK-LIST&quot;-bugs"><a id="Note"></a><a id="Note-on--Function-BLOCK-LIST--bugs"></a>Note on &quot;Function BLOCK LIST&quot; bugs</h3>

<p>Note that in at least some versions of Perl, support for the &quot;Filter BLOCK ...&quot; syntax is somewhat fragile. For example:</p>

<pre><code>    ... Filter( {y/aeiou/UAEIO/} @list );</code></pre>

<p>may give you this error:</p>

<pre><code>    Array found where operator expected</code></pre>

<p>which can be fixed by dropping the parentheses:</p>

<pre><code>    ... Filter {y/aeiou/UAEIO/} @list;</code></pre>

<p>So if you need or want to use parentheses when calling Filter, it is best to also include the <code>sub</code> keyword and the comma:</p>

<pre><code>    #         v &lt;--------- These ---------&gt; v
    ... Filter( sub {y/aeiou/UAEIO/}, @list );
    # require   ^^^ &lt;--- these ---&gt; ^ (sometimes)</code></pre>

<p>so your code will be portable to more versions of Perl.</p>

<h3 id="Examples">Examples</h3>

<p>Good code ignores &quot;invisible&quot; characters. So instead of just chomp()ing, consider removing all trailing whitespace:</p>

<pre><code>    my @lines= Filter { s/\s+$// } &lt;IN&gt;;</code></pre>

<p>or</p>

<pre><code>    my $line= Filter { s/\s+$// } scalar &lt;IN&gt;;</code></pre>

<p>[ Note that Filter can be used in a scalar context but always puts its arguments in a list context. So we need to use <code>scalar</code> or something similar if we want to read only one line at a time from <code>IN</code> above. ]</p>

<p>Want to sort strings that contain mixtures of letters and natural numbers (non-negative integers) both alphabetically and numerically at the same time? This simple way to do a &quot;natural&quot; sort is also one of the fastest. Great for sorting version numbers, file names, etc.:</p>

<pre><code>    my @sorted= Filter {
        s#\d{2}(\d+)#\1#g
    } sort Filter {
        s#(\d+)# sprintf &quot;%02d%s&quot;, length($1), $1 #g
    } @data;</code></pre>

<p>[ Note that at least some versions of Perl have a bug that breaks <code>sort</code> if you write <code>sub {</code> as part of building the list of items to be sorted but you don&#39;t provide a comparison routine. This bug means we can&#39;t write the previous code as:</p>

<pre><code>    my @sorted= Filter {
        s#\d{2}(\d+)#\1#g
    } sort Filter sub {
        s#(\d+)# sprintf &quot;%02d%s&quot;, length($1), $1 #g
    }, @data;</code></pre>

<p>because it will produce the following error:</p>

<pre><code>    Undefined subroutine in sort</code></pre>

<p>in some versions of Perl. Some versions of Perl may even require you to write it like this:</p>

<pre><code>    my @sorted= Filter {
        s#\d{2}(\d+)#\1#g
    } sort &amp;Filter( sub {
        s#(\d+)# sprintf &quot;%02d%s&quot;, length($1), $1 #g
    }, @data );</code></pre>

<p>Which is how I wrote it in ex/NaturalSort.plx. ]</p>

<p>Need to sort names? Then you&#39;ll probably want to ignore letter case and certain punctuation marks while still preserving both:</p>

<pre><code>    my @compare= Filter {tr/A-Z&#39;.,&quot;()/a-z/d} @names;
    my @indices= sort {$compare[$a] cmp $compare[$b]} 0..$#names;
    @names= @names[@indices];</code></pre>

<p>You can also roll your own simple HTML templating:</p>

<pre><code>    print Filter {
        s/%(\w*)%/expand($1)/g
    }   $cgi-&gt;...,
        ...
        $cgi-&gt;...;</code></pre>

<p>Note that it also also works correctly if you change how you output your HTML and accidentally switch from list to scalar context:</p>

<pre><code>    my $html= &#39;&#39;;
    ...
    $html .= Filter {
        s/%(\w*)%/expand($1)/g
    }   $cgi-&gt;...,
        ...
        $cgi-&gt;...;</code></pre>

<h3 id="Motivation">Motivation</h3>

<p>A reasonable use of map is:</p>

<pre><code>    @copy= map {lc} @list;</code></pre>

<p>which sets @copy to be a copy of @list but with all of the elements converted to lower case. But it is too easy to think that that could also be done like this:</p>

<pre><code>    @copy= map {tr/A-Z/a-z/} @list;  # Wrong</code></pre>

<p>The reason why these aren&#39;t the same is similar to why we write:</p>

<pre><code>    $str= lc $str;</code></pre>

<p>not</p>

<pre><code>    lc $str;  # Useless use of &#39;lc&#39; in void context</code></pre>

<p>and we write:</p>

<pre><code>    $str =~ tr/A-Z/a-z/;</code></pre>

<p>not</p>

<pre><code>    $new= ( $old =~ tr/A-Z/a-z/ );  # Wrong</code></pre>

<p>That is, many things (such as lc) return a modified copy of what they are given, but a few things (such as tr///, s///, chop, and chomp) modify what they are given <i>in-place</i>.</p>

<p>This distinction is so common that we have several ways of switching between the two forms. For example:</p>

<pre><code>        $two= $one + $other;
  # vs.
        $one += $other;</code></pre>

<p>or</p>

<pre><code>        $two= substr($one,0,4);
  # vs.
        substr($one,4)= &#39;&#39;;</code></pre>

<p>I&#39;ve even heard talk of adding some syntax to Perl to allow you to make things like <code>lc</code> become reflexive, similar to how += is the reflexive form of +.</p>

<p>But while many non-reflexive Perl operations have reflexive counterparts, there are a few reflexive Perl operations that don&#39;t really have non-reflexive counterparts: s///, tr///, chop, chomp.</p>

<p>You can write:</p>

<pre><code>        my $line= &lt;STDIN&gt;;
        chomp( $line );
  # or
        chomp( my $line= &lt;STDIN&gt; );</code></pre>

<p>but it somehow seems more natural to write:</p>

<pre><code>        my $line= chomp( &lt;STDIN&gt; );  # Wrong</code></pre>

<p>So, if you dislike hiding the variable declaration inside of a function call or dislike using two lines and repeating the variable name, then you can now use:</p>

<pre><code>        my $line= Filter {chomp} &#39;&#39;.&lt;STDIN&gt;;</code></pre>

<p>[ I used <code>&#39;&#39;.</code> to provide a scalar context so that only one line is read from STDIN. ]</p>

<p>Or, for a better example, consider these valid alternatives:</p>

<pre><code>        my @lines= &lt;STDIN&gt;;
        chomp( @lines );
  # or
        chomp( my @lines= &lt;STDIN&gt; );</code></pre>

<p>And what you might expect to work (but doesn&#39;t):</p>

<pre><code>        my @lines= chomp( &lt;STDIN&gt; );  # Wrong</code></pre>

<p>And what you can now use instead:</p>

<pre><code>        my @lines= Filter {chomp} &lt;STDIN&gt;;</code></pre>

<p>Here are some examples of ways to use map/grep correctly to get Filter&#39;s functionality:</p>

<pre><code>        Filter { CODE } @list
  # vs
        join &quot;&quot;, map { local($_)= $_; CODE; $_ } @list
  # vs
        join &quot;&quot;, grep { CODE; 1 } @{ [@list] }</code></pre>

<p>Not horribly complex, but enough that it is very easy to forget part of the solution, making for easy mistakes. I see mistakes related to this quite frequently and have made such mistakes myself several times.</p>

<p>Some (including me) would even consider the last form above to be an abuse (or misuse) of <code>grep</code>.</p>

<p>You can also use <code>for</code>/<code>foreach</code> to get the same results as Filter:</p>

<pre><code>        my @copy= Filter { CODE } @list;
  # vs
        STATEMENT  foreach  my @copy= @list;
  # or
        my @copy= @list;
        foreach(  @copy  ) {
            CODE;
        }</code></pre>

<h2 id="MapCar*"><a id="MapCar1"></a>MapCar*</h2>

<dl>

<dt id="MapCar(\&amp;@)"><a id="MapCar2"></a>MapCar(\&amp;@)</dt>
<dd>

</dd>
<dt id="MapCarU(\&amp;@)"><a id="MapCarU"></a>MapCarU(\&amp;@)</dt>
<dd>

</dd>
<dt id="MapCarE(\&amp;@)"><a id="MapCarE"></a>MapCarE(\&amp;@)</dt>
<dd>

</dd>
<dt id="MapCarMin(\&amp;@)"><a id="MapCarMin"></a>MapCarMin(\&amp;@)</dt>
<dd>

</dd>
</dl>

<h3 id="Usage1">Usage</h3>

<p>The MapCar* functions are all like <code>map</code> except they each loop over more than one list at the same time.</p>

<p>[ The name &quot;mapcar&quot; comes from LISP. As I understand it, &#39;car&#39; comes from the acronym for a register of the processor where LISP was first developed, one of two registers used to implement lists in LISP. I only mention this so you won&#39;t waste too much time trying to figure out what &quot;mapcar&quot; is supposed to mean. ]</p>

<p>The MapCar* functions all have prototype specifications of (\&amp;@).</p>

<p>This means that they demand that the first argument that you pass be a CODE reference. After that you should pass zero or more array references.</p>

<p>Your subroutine is called (in a list context) and is passed the first element of each of the arrays whose references you passed in (in the corresponding order). Any value(s) returned by your subroutine are pushed onto an array that will eventually be returned by MapCar*.</p>

<p>Next your subroutine is called and is passed the <b>second</b> element of each of the arrays and any value(s) returned are pushed onto the results array. Then the process is repeated with the <b>third</b> elements.</p>

<p>This continues until your subroutine has been passed all elements [except for some cases with MapCarMin()]. If the longest array whose reference you passed to MapCar() or MapCarU() contained $N elements, then your subroutine would get called $N times.</p>

<p>Finally, the MapCar* function returns the accumulated list of values. If called in a scalar context, the MapCar* function returns a reference to an array containing these values.</p>

<p>[ I feel that having <code>map</code> return a count when called in a scalar context is quite simply a mistake that was made when this feature was copied from <code>grep</code> without properly considering the consequences. Although it does make for the impressive and very impractical golf solution of:</p>

<pre><code>    $sum=map{(1)x$_}@ints;</code></pre>

<p>for adding up a list of natural numbers. q-: ]</p>

<h3 id="Differences">Differences</h3>

<p>The different MapCar* functions are only different in how they deal with being pqssed arrays that are not all of the same size.</p>

<p>If not all of your arrays are the same length, then MapCarU() will pass in <code>undef</code> for any values corresponding to arrays that didn&#39;t have enough values. The &quot;U&quot; in &quot;MapCarU&quot; stands for &quot;undef&quot;.</p>

<p>In contrast, MapCar() will simply leave out values for short arrays (just like I left the &quot;U&quot; out of its name).</p>

<p>MapCarE() will croak without ever calling your subroutine unless all of the arrays are the same length. It considers it an Error if your arrays are not of Equal length and so throws an Exception.</p>

<p>Finally, MapCarMin() only calls your subroutine as many times as there are elements in the <b>shortest</b> array.</p>

<p>In other words,</p>

<pre><code>    MapCarU \&amp;MySub, [1,undef,3], [4,5], [6,7,8]</code></pre>

<p>returns</p>

<pre><code>    ( MySub( 1, 4, 6 ),
      MySub( undef, 5, 7 ),
      MySub( 3, undef, 8 ),
    )</code></pre>

<p>While</p>

<pre><code>    MapCar \&amp;MySub, [1,undef,3], [4,5], [6,7,8]</code></pre>

<p>returns</p>

<pre><code>    ( MySub( 1, 4, 6 ),
      MySub( undef, 5, 7 ),
      MySub( 3, 8 ),
    )</code></pre>

<p>While</p>

<pre><code>    MapCarMin \&amp;MySub, [1,undef,3], [4,5], [6,7,8]</code></pre>

<p>returns</p>

<pre><code>    ( MySub( 1, 4, 6 ),
      MySub( undef, 5, 7 ),
    )</code></pre>

<p>And</p>

<pre><code>    MapCarE \&amp;MySub, [1,undef,3], [4,5], [6,7,8]</code></pre>

<p>dies with</p>

<pre><code>    MapCarE: Arrays with different sizes (3 and 2)</code></pre>

<h3 id="Examples1">Examples</h3>

<p>Transposing a two-dimensional matrix:</p>

<pre><code>    my @transposed= MapCarE {[@_]} @matrix;</code></pre>

<p>or, using references to the matrices and allowing for different row lengths:</p>

<pre><code>    my $transposed= MapCarU {[@_]} @$matrix;</code></pre>

<p>Formatting a date-time:</p>

<pre><code>    my $dateTime= join &#39;&#39;, MapCarE {
        sprintf &quot;%02d%s&quot;, pop()+pop(), pop()
    } [ (localtime)[5,4,3,2,1,0] ],
      [ 1900, 1, (0)x4 ],
      [ &#39;// ::&#39; =~ /./g, &#39;&#39; ];</code></pre>

<p>Same thing but not worrying about warnings for using undefined values:</p>

<pre><code>    my $dateTime= join &#39;&#39;, MapCarU {
        sprintf &quot;%02d%s&quot;, pop()+pop(), pop()
    } [ (localtime)[5,4,3,2,1,0] ],
      [ 1900, 1 ],
      [ &#39;// ::&#39; =~ /./g ];</code></pre>

<p>Combine with <code>map</code> to do matrix multiplication:</p>

<pre><code>    my @X= (
        [  1,  3 ],
        [  4, -1 ],
        [ -2,  2 ],
    );
    my @Y= (
        [ -6,  2, 5, -3 ],
        [  4, -1, 3,  1 ],
    );
    my @prod= map {
        my $row= $_;
        [
            map {
                my $sum= 0;
                $sum += $_   for  MapCarE {
                    pop() * pop();
                } $row, $_;
                $sum;
            } MapCarE {\@_} @Y;
        ]
    } @X;</code></pre>

<p>Report the top winners:</p>

<pre><code>    MapCarMin {
        print pop(), &quot; place goes to &quot;, pop(), &quot;.\n&quot;;
    } [qw( First Second Third Fourth )],
      \@winners;</code></pre>

<p>Same thing (scalar context):</p>

<pre><code>    my $report= MapCarMin {
        pop(), &quot; place goes to &quot;, pop(), &quot;.\n&quot;;
    } [qw( First Second Third Fourth )],
      \@winners;</code></pre>

<p>Displaying a duration:</p>

<pre><code>    my $ran= time() - $^T;
    my $desc= join &#39;, &#39;, reverse MapCar {
        my( $unit, $mult )= @_;
        my $part= $ran;
        if(  $mult  ) {
            $part %= $mult;
            $ran= int( $ran / $mult );
        }
        $unit .= &#39;s&#39;   if  1 != $part;
        $part ? &quot;$part $unit&quot; : ();
    } [ qw( sec min hour day week year ) ],
      [     60, 60, 24,   7,  52 ];
    $desc ||= &#39;&lt; 1 sec&#39;;
    print &quot;Script ran for $desc.\n&quot;;</code></pre>

<h2 id="NextPermute*"><a id="NextPermute1"></a>NextPermute*</h2>

<dl>

<dt id="NextPermute(\@)"><a id="NextPermute2"></a>NextPermute(\@)</dt>
<dd>

</dd>
<dt id="NextPermuteNum(\@)"><a id="NextPermuteNum"></a>NextPermuteNum(\@)</dt>
<dd>

</dd>
</dl>

<h3 id="Introduction">Introduction</h3>

<p>If you have a list of values, then a &quot;permutation&quot; of that list is the same values but not (necessarily) in the same order.</p>

<p>NextPermute() and NextPermuteNum() each provide very efficient ways of finding all of the (unique) permutations of a list (even if the list contains duplicate values).</p>

<h3 id="Usage2">Usage</h3>

<p>Each time you pass an array to a NextPermute* routine, the elements of the array are shifted around to give you a new permutation. If the elements of the array are in reverse-sorted order, then the array is reversed (in-place, making it sorted) and a false value is returned. Otherwise a true value is returned.</p>

<p>So, if you start out with a sorted array, then you can use that as your first permutation and then call NextPermute* to get the next permutation to use, until NextPermute* returns a false value (at which point your array has been returned to its original, sorted order).</p>

<p>So you would use NextPermute() like this:</p>

<pre><code>    my @list= sort GetValuesSomehow();
    do {
        DoSomethingWithPermutation( @list );
    } while(  NextPermute( @list )  );</code></pre>

<p>or, if your list only contains numbers, you could use NextPermuteNum() like this:</p>

<pre><code>    my @list= sort {$a&lt;=&gt;$b} GetNumbersSomehow();
    do {
        DoSomethingWithPermutation( @list );
    } while(  NextPermuteNum( @list )  );</code></pre>

<h3 id="Notes">Notes</h3>

<p>The NextPermute* functions each have a prototype specifications of (\@). This means that they demand that you pass them a single array which they will receive a reference to.</p>

<p>If you instead have a reference to an array, you&#39;ll need to use <code>@{ }</code> when calling a NextPermute* routine:</p>

<pre><code>    } while(  NextPermute( @{$av} )  );</code></pre>

<p>(or use one of several other techniques which I will leave the consideration of as an &quot;exercise&quot; for the more advanced readers of this manual).</p>

<p>Note that this particular use of a function prototype is one that I am not completely comfortable with. I am tempted to remove the prototype and force you to create the reference yourself before/when calling these functions:</p>

<pre><code>    } while(  NextPermute( \@list )  );   # Wrong</code></pre>

<p>because</p>

<ul>

<li><p>It makes it obvious to the reader of the code that a reference to the array is what is being used by the routine. This makes the reader more likely to realize/suspect that the array is being modified in-place.</p>

</li>
<li><p>Many/most uses of Perl function prototypes are more trouble than they are worth. This makes using even the less problematic cases often not a good idea.</p>

</li>
</ul>

<p>However, I have decided to use a prototype here because:</p>

<ul>

<li><p>Several other functions from this module already use prototypes to good advantage, enough advantage that I&#39;d hate to lose it.</p>

</li>
<li><p>Removing the prototype would require the addition of argument-checking code that would get run each time a permutation is computed, somewhat slowing down what is currently quite fast.</p>

</li>
<li><p>The compile-time checking provided by the prototype can save develop time over a run-time check by pointing out mistakes sooner.</p>

</li>
</ul>

<h3 id="Features">Features</h3>

<p>There are several features to NextPermute* that can be advantages over other methods of finding permutations.</p>

<dl>

<dt id="Iterators-No-huge-memory-requirements"><a id="Iterators"></a>Iterators - No huge memory requirements</dt>
<dd>

<p>Some permutation generators return the full set of all permutations (as a huge list of lists). Your input list doesn&#39;t have to be very big at all for the resulting set to be too large to fit in your available memory.</p>

<p>So the NextPermute* routines return each permutation, one at a time, so you can process them all (eventually) without the need for lots of memory.</p>

<p>A programming object that gives you access to things one-at-a-time is called an &quot;iterator&quot;.</p>

</dd>
<dt id="No-context-Hardly-any-memory-required"><a id="No"></a>No context - Hardly any memory required</dt>
<dd>

<p>The NextPermute* routines require no extra memory in the way of context or lists to keep track of while constructing the permutations.</p>

<p>Each call to a NextPermute* routine shuffles the items in the list <b>in-place</b>, never making copies of more than a couple of values at a time (when it swaps them).</p>

<p>[ This also means you don&#39;t have to bother with creating an object to do the iterating. ]</p>

</dd>
<dt id="Handles-duplicate-values"><a id="Handles"></a>Handles duplicate values</dt>
<dd>

<p>Unlike most permutation generators you are likely to find in Perl, both NextPermute* routines correctly deal with lists containing duplicate values.</p>

<p>The following example:</p>

<pre><code>    my @list= ( 3, 3, 3, 3 );
    do {
        print &quot;@list\n&quot;;
    } while(  NextPermute( @list )  );</code></pre>

<p>will only print the one line, &quot;3 3 3 3\n&quot;, because NextPermute() quickly determines that there are no other unique permutations.</p>

<p>Try out the demonstration program included in the &quot;ex&quot; subdirectory of the source distribution of this module:</p>

<pre><code>    &gt; perl ex/Permute.plx tool
    1: loot
    2: loto
    3: ltoo
    4: olot
    5: olto
    6: oolt
    7: ootl
    8: otlo
    9: otol
    10: tloo
    11: tolo
    12: tool</code></pre>

<p>Most permutation generators would have listed each of those twice (thinking that swapping an &quot;o&quot; with another &quot;o&quot; made a new permutation). Or consider:</p>

<pre><code>    &gt; perl ex/Permute.plx noon
    1: nnoo
    2: nono
    3: noon
    4: onno
    5: onon
    6: oonn</code></pre>

<p>Most permutation generators would have listed each of those <b>four</b> times.</p>

<p>Note that using a hash to eliminate duplicates would require a hash table big enough to hold all of the (unique) permutations and so would defeat the purpose of iterating. NextPermute* does not use a hash to avoid duplicates.</p>

</dd>
<dt id="Generated-in-sorted-order"><a id="Generated"></a>Generated in sorted order</dt>
<dd>

<p>If you were to run code like:</p>

<pre><code>    my @list= sort GetValuesSomehow();
    do {
        print join(&#39;&#39;,@lista, $/);
    } while(  NextPermute( @list )  );</code></pre>

<p>then the lines output would be sorted (assuming none of the values in @list contained newlines. This may be convenient in some corcumstances.</p>

<p>That is, the permutations are generated in sorted order. The first permutations have the lowest values at the front of the list. As you iterate, larger values are shifted to be in front of smaller values, starting at the back of the list. So the value at the very front of the list will change the fewest times (once for each unique value in the list), while the value at the very end of the list changes between most iterations.</p>

</dd>
<dt id="Fast">Fast</dt>
<dd>

<p>If you don&#39;t have to deal with duplicate values, then Algorithm::Permute provides some routines written in C (which makes them harder to install but about twice as fast to run as the NextPermute* routines) that you can use.</p>

<p>Algorithm::Permute also includes some fun benchmarks comparing different Perl ways of finding permutations. I found NextPermute to be faster than any of the routines included in those benchmarks except for the ones written in C that I mentioned above. Though none of the benchmarked routines deal with duplicates.</p>

</dd>
</dl>

<h3 id="Notes1">Notes</h3>

<p>Note that NextPermute() considers two values (say $x and $y) to be duplicates if (and only if) <code>$x eq $y</code>.</p>

<p>NextPermuteNum() considers $x and $y to be duplicates if <code>$x == $y</code>.</p>

<p>If you have a list of floating point numbers to permute, you might want to use NextPermute() [instead of NextPermuteNum()] as it is easy to end up with $x and $y that both display the same (say as &quot;0.1&quot;) but are <b>just barely</b> not equal numerically. Thus $x and $y would <i>look</i> equal and it would be true that <code>$x eq $y</code> but also true that <code>$x != $y</code>. So NextPermute() would consider them to be duplicates but NextPermuteNum() would not.</p>

<p>For example, $x could be slightly more than 1/10, likely about 0.1000000000000000056, while $y is slightly more at about 0.0999999999999999917 (both of which will be displayed as &quot;0.1&quot; by Perl and be considered <code>eq</code> (on most platforms):</p>

<pre><code>    &gt; perl -w -Mstrict
    my $x= 0.1000000000000000056;
    my $y= 0.0999999999999999917;
    print &quot;x=$x\ny=$y\n&quot;;
    print &quot;are eq\n&quot;   if  $x eq $y;
    print &quot;are ==\n&quot;   if  $x == $y;
    print &quot;are !=\n&quot;   if  $x != $y;
    &lt;EOF&gt;
    x=0.1
    y=0.1
    are eq
    are !=</code></pre>

<h2 id="NestedLoops1">NestedLoops</h2>

<h3 id="Introduction1">Introduction</h3>

<p>Makes it easy to simulate loops nested to an arbitrary depth.</p>

<p>It is easy to write code like:</p>

<pre><code>    for my $a (  0..$N  ) {
     for my $b (  $a+1..$N  ) {
      for my $c (  $b+1..$N  ) {
          Stuff( $a, $b, $c );
      }
     }
    }</code></pre>

<p>But what if you want the user to tell you how many loops to nest together? The above code can be replaced with:</p>

<pre><code>    use Algorithm::Loops qw( NestedLoops );

    my $depth= 3;
    NestedLoops(
        [   [ 0..$N ],
            ( sub { [$_+1..$N] } ) x ($depth-1),
        ],
        \&amp;Stuff,
    );</code></pre>

<p>Then you only have to change $depth to 4 to get the same results as:</p>

<pre><code>    for my $a (  0..$N  ) {
     for my $b (  $a+1..$N  ) {
      for my $c (  $b+1..$N  ) {
       for my $d (  $c+1..$N  ) {
          Stuff( $a, $b, $c, $d );
       }
      }
     }
    }</code></pre>

<h3 id="Usage3">Usage</h3>

<p>The first argument to NestedLoops() is required and must be a reference to an array. Each element of the array specifies the values for a single loop to iterate over. The first element describes the outermost loop. The last element describes the innermost loop.</p>

<p>If the next argument to NestedLoops is a hash reference, then it specifies more advanced options. This argument can be omitted if you don&#39;t need it.</p>

<p>If the last argument to NestedLoops is a code reference, then it will be run inside the simulated loops. If you don&#39;t pass in this code reference, then NestedLoops returns an iterator (described later) so you can iterate without the restrictions of using a call-back.</p>

<p>So the possible ways to call NestedLoops are:</p>

<pre><code>    $iter= NestedLoops( \@Loops );
    $iter= NestedLoops( \@Loops, \%Opts );
    ...    NestedLoops( \@Loops, \%Opts, \&amp;Code );
    ...    NestedLoops( \@Loops,         \&amp;Code );</code></pre>

<p>The &quot;...&quot;s above show that, when the final code reference is provided, NestedLoops can return a few different types of information.</p>

<p>In a void context, NestedLoops simply iterates and calls the provided code, discarding any values it returns. (Calling NestedLoops in a void context without passing a final code reference is a fatal error.)</p>

<p>In a list context, NestedLoops <code>push</code>es the values returned by each call to \&amp;Code onto an array and then returns (copies of the values from) that array.</p>

<p>In a scalar contetx, NestedLoops keeps a running total of the number of values returned by each call to \&amp;Code and then returns this total. The value is the same as if you had called NestedLoops in a list context and counted the number of values returned (except for using less memory).</p>

<p>Note that \&amp;Code is called in a list context no matter what context NestedLoops was called in (in the current implementation).</p>

<p>In summary:</p>

<pre><code>    NestedLoops( \@loops, \%opts, \&amp;code );
    $count= NestedLoops( \@loops, \%opts, \&amp;code );
    @results= NestedLoops( \@loops, \%opts, \&amp;code );</code></pre>

<h4 id="\@Loops"><a id="Loops"></a>\@Loops</h4>

<p>Each element of @Loops can be</p>

<dl>

<dt id="an-array-refernce"><a id="an"></a>an array refernce</dt>
<dd>

<p>which means the loop will iterate over the elements of that array,</p>

</dd>
<dt id="a-code-refernce"><a id="a"></a>a code refernce</dt>
<dd>

<p>to a subroutine that will return a reference to the array to loop over.</p>

</dd>
</dl>

<p>You don&#39;t have to use a reference to a named array. You can, of course, construct a reference to an anonymous array using <code>[...]</code>, as shown in most of the examples. You can also use any other type of expression that rerurns an array reference.</p>

<h4 id="\%Opts"><a id="Opts"></a>\%Opts</h4>

<p>If %Opts is passed in, then it should only zero or more of the following keys. How NestedLoops interprets the values associated with each key are described below.</p>

<dl>

<dt id="OnlyWhen-=&gt;-$Boolean"><a id="OnlyWhen"></a><a id="OnlyWhen----Boolean"></a>OnlyWhen =&gt; $Boolean</dt>
<dd>

</dd>
<dt id="OnlyWhen-=&gt;-\&amp;Test"><a id="OnlyWhen1"></a><a id="OnlyWhen----Test"></a>OnlyWhen =&gt; \&amp;Test</dt>
<dd>

<p>Value must either be a Boolean value or a reference to a subroutine that will return a Boolean value.</p>

<p>Specifying a true value is the same as specifying a routine that always returns a true value. Specifying a false value gives you the default behavior (as if you did not include the OnlyWhen key at all).</p>

<p>If it is a code reference, then it is called each time a new item is selected by any of the loops. The list of selected items is passed in.</p>

<p>The Boolean value returned says whether to use the list of selected values. That is, a true value causes either \&amp;Code to be called (if specified) or the list to be returned by the iterator (if \&amp;Code was not specified).</p>

<p>If this key does not exist (or is specified with a false value), then a default subroutine is used, like:</p>

<pre><code>    sub { return @_ == @Loops }</code></pre>

<p>That is, only complete lists are used (by default). So:</p>

<pre><code>    my @list= NestedLoops(
        [  ( [ 1..3 ] ) x 3  ],
        {  OnlyWhen =&gt; 0  },
        sub { &quot;@_&quot; },
    );</code></pre>

<p>is similar to:</p>

<pre><code>    my @list= qw/ 111 112 113 121 122 123 131 132 133 211 212 ... /;</code></pre>

<p>while</p>

<pre><code>    my @list= NestedLoops(
        [  ( [ 1..3 ] ) x 3  ],
        {  OnlyWhen =&gt; 1  },
        sub { &quot;@_&quot; },
    );</code></pre>

<p>is similar to:</p>

<pre><code>    my @list= qw/ 1 11 111 112 113 12 121 122 123
                  13 131 132 133 2 21 211 212 ... /;</code></pre>

<p>Another example:</p>

<pre><code>    NestedLoops(
        [  ( [ 1..3 ] ) x 3  ],
        { OnlyWhen =&gt; 1 },
        \&amp;Stuff,
    );</code></pre>

<p>is similar to:</p>

<pre><code>    for my $a (  1..3  ) {
        Stuff( $a );
        for my $b (  1..3  ) {
            Stuff( $a, $b );
            for my $c (  1..3  ) {
                Stuff( $a, $b, $c );
            }
        }
    }</code></pre>

<p>Last example:</p>

<pre><code>    NestedLoops(
        [  ( [ 1..3 ] ) x 3  ],
        { OnlyWhen =&gt; \&amp;Test },
        \&amp;Stuff,
    );</code></pre>

<p>is similar to:</p>

<pre><code>    for my $a (  1..3  ) {
        Stuff( $a )   if  Test( $a );
        for my $b (  1..3  ) {
            Stuff( $a, $b )   if  Test( $a, $b );
            for my $c (  1..3  ) {
                Stuff( $a, $b, $c )
                    if  Test( $a, $b, $c );
            }
        }
    }</code></pre>

</dd>
</dl>

<h4 id="\&amp;Code"><a id="Code"></a>\&amp;Code</h4>

<p>The subroutine that gets called for each iteration.</p>

<h4 id="Iterator">Iterator</h4>

<p>If you don&#39;t pass in a final code reference to NestedLoops, then NestedLoops will return an iterator to you (without having performed any iterations yet).</p>

<p>The iterator is a code reference. Each time you call it, it returns the next list of selected values. Any arguments you pass in are ignored (at least in this release).</p>

<h3 id="Examples2">Examples</h3>

<h4 id="Finding-non-repeating-sequences-of-digits."><a id="Finding"></a><a id="Finding-non-repeating-sequences-of-digits"></a>Finding non-repeating sequences of digits.</h4>

<p>One way would be to loop over all digit combinations but only selecting ones without repeats:</p>

<pre><code>    use Algorithm::Loops qw/ NestedLoops /;
    $|= 1;
    my $len= 3;
    my $verbose= 1;
    my $count= NestedLoops(
        [   ( [0..9] ) x $len  ],
        {   OnlyWhen =&gt; sub {
                    $len == @_
                &amp;&amp;  join(&#39;&#39;,@_) !~ /(.).*?\1/;
            #or &amp;&amp;  @_ == keys %{{@_,reverse@_}};
            }
        },
        sub {
            print &quot;@_\n&quot;   if  $verbose;
            return 1;
        },
    );
    print &quot;$count non-repeating $len-digit sequences.\n&quot;;

    0 1 2
    0 1 3
    0 1 4
    0 1 5
    0 1 6
    0 1 7
    0 1 8
    0 1 9
    0 2 1
    ...
    9 8 5
    9 8 6
    9 8 7
    720 non-repeating 3-digit sequences.</code></pre>

<p>But it would be nice to not waste time looping over, for example (2,1,2,0,0) through (2,1,2,9,9). That is, don&#39;t even pick 2 as the third value if we already picked 2 as the first.</p>

<p>A clever way to do that is to only iterate over lists where the digits <i>increase</i> from left to right. That will give us all <i>sets</i> of non-repeating digits and then we find all permutations of each:</p>

<pre><code>    use Algorithm::Loops qw/ NestedLoops NextPermute /;
    $|= 1;
    my $len= 3;
    my $verbose= 1;
    my $iter= NestedLoops(
        [   [0..9],
            ( sub { [$_+1..9] } ) x ($len-1),
        ],
    );
    my $count= 0;
    my @list;
    while(  @list= $iter-&gt;()  ) {
        do {
            ++$count;
            print &quot;@list\n&quot;   if  $verbose;
        } while( NextPermute(@list) );
    }
    print &quot;$count non-repeating $len-digit sequences.\n&quot;;

    0 1 2
    0 2 1
    1 0 2
    1 2 0
    2 0 1
    2 1 0
    0 1 3
    0 3 1
    1 0 3
    1 3 0
    3 0 1
    3 1 0
    0 1 4
    0 4 1
    ...
    9 6 8
    9 8 6
    7 8 9
    7 9 8
    8 7 9
    8 9 7
    9 7 8
    9 8 7
    720 non-repeating 3-digit sequences.</code></pre>

<p>A third way is to construct the list of values to loop over by excluding values already selected:</p>

<pre><code>    use Algorithm::Loops qw/ NestedLoops /;
    $|= 1;
    my $len= 3;
    my $verbose= 1;
    my $count= NestedLoops(
        [   [0..9],
            ( sub {
                my %used;
                @used{@_}= (1) x @_;
                return [ grep !$used{$_}, 0..9 ];
            } ) x ($len-1),
        ],
        sub {
            print &quot;@_\n&quot;   if  $verbose;
            return 1;
        },
    );
    print &quot;$count non-repeating $len-digit sequences.\n&quot;;

    0 1 2
    0 1 3
    0 1 4
    0 1 5
    0 1 6
    0 1 7
    0 1 8
    0 1 9
    0 2 1
    0 2 3
    ...
    9 7 8
    9 8 0
    9 8 1
    9 8 2
    9 8 3
    9 8 4
    9 8 5
    9 8 6
    9 8 7
    720 non-repeating 3-digit sequences.</code></pre>

<p>Future releases of this module may add features to makes these last two methods easier to write.</p>

<div class="pod-errors"><p>1 POD Error</p><div class="pod-errors-detail"><p>The following errors were encountered while parsing the POD:</p><dl><dt>Around line 955:</dt><dd><p>&#39;=item&#39; outside of any &#39;=over&#39;</p></dd></dl></div></div></div>

<div id="metacpan_install-instructions-dialog" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Module Install Instructions</h4>
      </div>
      <div class="modal-body">
        <p>To install Algorithm::Loops, copy and paste the appropriate command in to your terminal.</p>
        <p><a href="https://metacpan.org/dist/App-cpanminus/view/bin/cpanm">cpanm</a></p>
        <pre><code>cpanm Algorithm::Loops</code></pre>
        <p><a href="https://metacpan.org/pod/CPAN">CPAN shell</a></p>
        <pre><code>perl -MCPAN -e shell
install Algorithm::Loops</code></pre>
        <p>For more information on module installation, please visit <a href="https://www.cpan.org/modules/INSTALL.html">the detailed CPAN module installation guide</a>.</p>
      </div>
      <div class="modal-footer">
        <a href="./Algorithm::Loops.html#" data-dismiss="modal" class="btn">Close</a>
      </div>
    </div>
  </div>
</div>
          </main>
          <div class="content-pagination">
          </div>
        </div>
        <footer class="footer">
          <div class="footer-container">
            <div class="footer-social">
              <div class="footer-link footer-logo">
                <a href="https://metacpan.org/">
                  <img src="https://metacpan.org/static/images/metacpan-logo.svg" alt="MetaCPAN" />
                </a>
              </div>
              <a class="footer-social-link" href="https://github.com/metacpan">
                <i class="fab fa-github-square"></i>
              </a>
              <a class="footer-social-link" href="https://fosstodon.org/@metacpan">
                <i class="fab fa-mastodon"></i>
              </a>
            </div>
            <div class="footer-links">
              <div class="footer-link">
                  <a href="https://metacpan.org/about">About</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/about/sponsors">Sponsor</a>
              </div>
              <div class="footer-link">
                  <a href="https://grep.metacpan.org">grep::cpan</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/recent">Recent</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/about/faq">FAQ</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/tools">Tools</a>
              </div>
              <div class="footer-link">
                  <a href="https://fastapi.metacpan.org/">API</a>
              </div>
              <div class="footer-link">
                  <a href="https://www.perl.org/">Perl.org</a>
              </div>
            </div>
            <div class="footer-sponsors">
              <a class="footer-sponsor-link" target="_blank" href="https://www.bytemark.co.uk/" rel="noopener">
                <img class="footer-sponsor-bytemark" src="https://metacpan.org/static/images/sponsors/bytemark_logo.svg" alt="Bytemark logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://www.liquidweb.com/" rel="noopener">
                <img class="footer-sponsor-liquidweb" src="https://metacpan.org/static/images/sponsors/liquidweb_logo.png" alt="liquidweb logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://deriv.com/careers/" rel="noopener">
                <img class="footer-sponsor-deriv" src="https://metacpan.org/static/images/sponsors/deriv.svg" alt="Deriv logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://geocode.xyz" rel="noopener">
                <img class="footer-sponsor-geocode" src="https://metacpan.org/static/images/sponsors/geocodelogo.svg" alt="Geocode logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://www.fastly.com/" rel="noopener">
                <img class="footer-sponsor-fastly" src="https://metacpan.org/static/images/sponsors/fastly_logo.svg" alt="Fastly logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://opencagedata.com" rel="noopener">
                <img class="footer-sponsor-opencage" src="https://metacpan.org/static/images/sponsors/open-cage.svg" alt="OpenCage logo">
              </a>
            </div>
          </div>
        </footer>
        <div class="modal fade" tabindex="-1" role="dialog" id="metacpan_keyboard-shortcuts">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Keyboard Shortcuts</h4>
              </div>
              <div class="modal-body row">
<div class="col-md-6">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>Global</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>s</kbd>
        </td>
        <td>Focus search bar</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>?</kbd>
        </td>
        <td>Bring up this help dialog</td>
      </tr>
    </tbody>
  </table>

  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>GitHub</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>p</kbd>
        </td>
        <td>Go to pull requests</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>i</kbd>
        </td>
        <td>go to github issues (only if github is preferred repository)</td>
      </tr>
    </tbody>
  </table>
</div>

<div class="col-md-6">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>POD</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>a</kbd>
        </td>
        <td>Go to author</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>c</kbd>
        </td>
        <td>Go to changes</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>i</kbd>
        </td>
        <td>Go to issues</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>d</kbd>
        </td>
        <td>Go to dist</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>r</kbd>
        </td>
        <td>Go to repository/SCM</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>s</kbd>
        </td>
        <td>Go to source</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>b</kbd>
        </td>
        <td>Go to file browse</td>
      </tr>

    </tbody>
  </table>
</div>

<div class="col-md-12">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>Search terms</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><em>module:</em> (e.g. <a href="https://metacpan.org/search?q=module%3APlugin">module:Plugin</a>)</td>
      </tr>
      <tr>
        <td><em>distribution:</em> (e.g. <a href="https://metacpan.org/search?q=distribution%3ADancer+auth">distribution:Dancer auth</a>)</td>
      </tr>
      <tr>
        <td><em>author:</em> (e.g. <a href="https://metacpan.org/search?q=author%3ASONGMU+Redis">author:SONGMU Redis</a>)</td>
      </tr>
      <tr>
        <td><em>version:</em> (e.g. <a href="https://metacpan.org/search?q=version%3A1.00">version:1.00</a>)</td>
      </tr>
    </tbody>
  </table>
</div>
              </div>
              <div class="modal-footer"></div>
            </div>
          </div>
        </div>
    </body>
</html>
